<template>
  <div class="question-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>问卷管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="createNewQuestion"
          >新建问卷</el-button
        >
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="问卷名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入问卷名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="问卷类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择问卷类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in typeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.delFlag"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="'1'" />
            <el-option label="禁用" :value="'0'" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 问卷列表 -->
    <div class="question-list">
      <el-table
        :data="questionList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="问卷名称" min-width="200">
          <template #default="{ row }">
            <div class="question-name">
              <span class="name-text">{{ row.name }}</span>
              <el-tag
                v-if="row.typeName"
                :type="getTypeTagType(row.type)"
                size="small"
                style="margin-left: 8px"
              >
                {{ row.typeName }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.delFlag === '1' ? 'success' : 'danger'">
              {{ row.delFlag === "1" ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handlePreview(row)">
              预览
            </el-button>
            <el-button
              :type="row.delFlag === '1' ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.delFlag === "1" ? "禁用" : "启用" }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="问卷预览"
      width="70%"
      top="5vh"
      @close="handlePreviewClose"
    >
      <div class="form-preview" v-loading="previewLoading">
        <!-- 问卷标题 -->
        <div class="preview-title">
          <h3>{{ questionInfo.name }}</h3>
        </div>
        <!-- 模拟画布容器 -->
        <div
          class="preview-canvas"
          :style="{
            width: canvasSize.width + 'px',
            height: canvasSize.height + 'px',
          }"
        >
          <div
            v-for="item in previewComponents.filter((c) => !c.parentId)"
            :key="item.id"
            class="preview-component"
            v-show="!isComponentHidden(item.id)"
            :style="getComponentStyle(item)"
          >
            <FormComponent
              :component="{
                ...item,
                value: previewData[item.props.field || item.id],
              }"
              :mutex-state="mutexState"
              :is-preview="true"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="handlePreviewClose">关闭</el-button>
        <el-button @click="handleSubmit" type="primary">提交表单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getQuestionStores, getQuestionById } from "@/api/home";
import { useRouter } from "vue-router";
import FormComponent from "@/views/lowCode/components/FormComponent.vue";
import type { CanvasComponent, MutexRule } from "@/views/lowCode/types";

const router = useRouter();

// 问卷类型选项
const typeOptions = [
  { label: "糖尿病", value: 1 },
  { label: "高血压", value: 2 },
  { label: "心脏病", value: 3 },
  { label: "其他", value: 4 },
];

// 响应式数据
const loading = ref(false);
const questionList = ref<any[]>([]);
const selectedQuestions = ref<any[]>([]);
const previewVisible = ref(false);
const previewData = ref<Record<string, any>>({});
const previewComponents = ref<CanvasComponent[]>([]);
const previewLoading = ref(false);
const questionInfo = ref<any>({});

// 互斥状态管理
const mutexState = ref<Map<string, boolean>>(new Map());

// 搜索表单
const searchForm = reactive({
  name: "",
  type: "",
  delFlag: "",
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 获取问卷列表
const fetchQuestionList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm,
    };

    const response = await getQuestionStores(params);
    questionList.value = response;
    console.log(response);
  } catch (error) {
    console.error("获取问卷列表失败:", error);
    ElMessage.error("获取问卷列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchQuestionList();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    type: "",
    delFlag: "",
  });
  pagination.currentPage = 1;
  fetchQuestionList();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchQuestionList();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchQuestionList();
};

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedQuestions.value = selection;
};

// 新建问卷
const createNewQuestion = () => {
  router.push("/lowCode");
};

// 编辑问卷
const handleEdit = (row: any) => {
  // 跳转到低代码编辑器，并传递问卷数据
  router.push({
    path: "/lowCode",
    query: {
      id: row._id,
      mode: "edit",
    },
  });
};

// 预览问卷
const handlePreview = async (row: any) => {
  // 构建预览页面的URL，使用独立入口
  const previewUrl = `${window.location.origin}/preview.html#/?id=${row._id}&mode=preview`
  window.open(previewUrl, '_blank')
  // previewData.value = row;
  // previewVisible.value = true;
  // previewLoading.value = true;

  // try {
  //   const response = await getQuestionById({ id: row._id });
  //   console.log('预览数据:', response);
  //   questionInfo.value = response;
  //   if (response && response.question) {
  //     // 解析问卷数据
  //     const questionData = JSON.parse(response.question);
  //     if (Array.isArray(questionData)) {
  //       previewComponents.value = questionData;
  //       // 初始化预览数据
  //       initPreviewData();
  //       // 检查互斥规则
  //       checkMutexRules();
  //     } else {
  //       previewComponents.value = [];
  //       ElMessage.warning('问卷数据格式不正确');
  //     }
  //   } else {
  //     previewComponents.value = [];
  //     ElMessage.warning('未找到问卷数据');
  //   }
  // } catch (error) {
  //   console.error('获取问卷数据失败:', error);
  //   ElMessage.error('获取问卷数据失败');
  //   previewComponents.value = [];
  // } finally {
  //   previewLoading.value = false;
  // }
};

// 关闭预览弹窗
const handlePreviewClose = () => {
  previewComponents.value = [];
  previewData.value = {};
  previewLoading.value = false;
  previewVisible.value = false;
  mutexState.value.clear();
};

// 计算画布尺寸
const canvasSize = computed(() => {
  if (previewComponents.value.length === 0) {
    return { width: 800, height: 600 };
  }

  let maxX = 0;
  let maxY = 0;

  previewComponents.value.forEach((component) => {
    // 计算组件实际宽度
    let componentWidth: number;
    if (component.props.widthType === "custom" && component.props.customWidth) {
      componentWidth = component.props.customWidth;
    } else if (component.props.widthType === "full") {
      // 铺满模式使用一个合理的默认宽度来计算画布尺寸
      componentWidth = Math.max(component.size.width, 300);
    } else {
      componentWidth = component.size.width;
    }

    const right = component.position.x + componentWidth;
    const bottom = component.position.y + component.size.height;
    maxX = Math.max(maxX, right);
    maxY = Math.max(maxY, bottom);
  });

  return {
    width: Math.max(800, maxX + 50),
    height: Math.max(600, maxY + 50),
  };
});

// 获取组件样式（模拟画布布局）
const getComponentStyle = (component: CanvasComponent) => {
  // 计算组件宽度
  let componentWidth: string;
  if (component.props.widthType === "custom" && component.props.customWidth) {
    componentWidth = component.props.customWidth + "px";
  } else if (component.props.widthType === "full") {
    componentWidth = "100%";
  } else {
    componentWidth = component.size.width + "px";
  }

  return {
    // position: 'absolute' as const,
    // left: component.position.x + 'px',
    // top: component.position.y + 'px',
    width: componentWidth,
    height: component.size.height + "px",
    zIndex: 1,
  };
};

// 检查互斥规则
const checkMutexRules = () => {
  // 重置所有组件的隐藏状态
  mutexState.value.clear();

  // 遍历所有组件，检查互斥规则
  previewComponents.value.forEach((component) => {
    if (
      component.props.mutexConfig?.enabled &&
      component.props.mutexConfig.rules
    ) {
      // 使用 field 属性作为 key，如果没有 field 则使用 id 作为后备
      const key = component.props.field || component.id;
      const currentValue = previewData.value[key];
      console.log(
        `预览中检查组件 ${component.props.label} 的值:`,
        currentValue
      );

      const matchingRule = component.props.mutexConfig.rules.find(
        (rule: MutexRule) => rule.value === currentValue
      );

      if (matchingRule) {
        console.log(
          `预览中找到匹配规则，隐藏组件:`,
          matchingRule.hiddenComponents
        );
        // 隐藏指定的组件（直接使用组件ID）
        matchingRule.hiddenComponents.forEach((hiddenComponentId: string) => {
          mutexState.value.set(hiddenComponentId, true);
        });
      }
    }
  });
};

// 处理组件值变化
const handleComponentValueChange = (componentKey: string, value: any) => {
  previewData.value[componentKey] = value;
  // 重新检查互斥规则
  checkMutexRules();
};

// 检查组件是否被隐藏
const isComponentHidden = (componentId: string): boolean => {
  return mutexState.value.get(componentId) || false;
};

// 初始化预览数据
const initPreviewData = () => {
  previewData.value = {};
  previewComponents.value.forEach((component) => {
    // 使用 field 属性作为 key，如果没有 field 则使用 id 作为后备
    const key = component.props.field || component.id;
    previewData.value[key] = getDefaultValue(component.type);
  });
};

// 获取组件默认值
const getDefaultValue = (type: string): any => {
  // 统一按照 input 组件的标准，所有组件默认值都为空字符串
  switch (type) {
    case "checkbox":
      return []; // 多选框保持数组类型
    case "radio":
      return ""; // 单选框改为空字符串
    case "select":
      return ""; // 下拉选择改为空字符串
    case "number":
      return ""; // 数字输入改为空字符串
    case "date":
      return ""; // 日期选择保持空字符串
    default:
      return ""; // 其他所有组件都为空字符串
  }
};

// 提交表单
const handleSubmit = () => {
  console.log("表单数据:", previewData.value);
  ElMessage.success("表单提交成功，请查看控制台");
  handlePreviewClose();
};

// 切换状态
const handleToggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.delFlag === "1" ? "禁用" : "启用"}该问卷吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 这里需要调用切换状态的API
    // const response = await toggleQuestionStatus(row.id, row.delFlag === 1 ? 0 : 1)
    // if (response.code === 200) {
    //   ElMessage.success('操作成功')
    //   fetchQuestionList()
    // }

    ElMessage.success("操作成功");
    fetchQuestionList();
  } catch (error) {
    // 用户取消操作
  }
};

// 删除问卷
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要删除该问卷吗？删除后无法恢复", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 这里需要调用删除API
    // const response = await deleteQuestion(row.id)
    // if (response.code === 200) {
    //   ElMessage.success('删除成功')
    //   fetchQuestionList()
    // }

    ElMessage.success("删除成功");
    fetchQuestionList();
  } catch (error) {
    // 用户取消操作
  }
};

// 获取类型标签样式
const getTypeTagType = (type: number) => {
  switch (type) {
    case 1:
      return "success";
    case 2:
      return "warning";
    case 3:
      return "danger";
    default:
      return "info";
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN");
};

// 页面加载时获取数据
onMounted(() => {
  fetchQuestionList();
});
</script>

<style lang="scss">
.question-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .question-list {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .question-name {
      display: flex;
      align-items: center;

      .name-text {
        font-weight: 500;
        color: #303133;
      }
    }

    .pagination-wrapper {
      padding: 20px;
      display: flex;
      justify-content: center;
    }
  }

  .form-preview {
    height: 600px;
    overflow: auto;
    overflow-x: hidden;
    border: 1px solid #e4e7ed;
    width: 850px;
    padding: 20px;
    margin: 0 auto;
    .preview-title {
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .preview-canvas {
      position: relative;
      background: white;
      border-radius: 4px;
      overflow: auto;
      margin: 16px;
      min-width: 800px;
      min-height: 1200px;
      margin: 0 auto;
      &:hover {
        border-color: #409eff;
      }
    }

    .preview-component {
      // position: absolute;
      border: 1px dashed transparent;
      border-radius: 4px;
      margin-bottom: 15px;
      &:hover {
        border-color: transparent;
      }
    }
    .form-component {
      &:hover {
        border: none !important;
        outline: none !important;
      }
    }
    .grid-item {
      &:hover {
        background-color: transparent !important;
      }
    }
  }
}
</style>
